package com.example.backblog.config;

import cn.hutool.json.JSONUtil;
import com.example.backblog.util.JsonOutPutUtil;
import com.example.backblog.vo.ApiResult;
import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Component
@Log4j2
public class RateLimitInterceptor implements HandlerInterceptor {
    // 创建一个限流器
    // 每秒多少个请求
    private final RateLimiter rateLimiter = RateLimiter.create(50.0);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean acquire = rateLimiter.tryAcquire(500, TimeUnit.MILLISECONDS);
        if(acquire){
            return true;
        }else{
            response.setStatus(500);
            log.info("超出限制");
            JsonOutPutUtil.writeJsonToStream(response.getOutputStream(), ApiResult.error("请求太多，请稍后重试"));
            return false;
        }
    }
}
